package com.hwj.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.hwj.entity.Chat;
import com.hwj.entity.User;
import com.hwj.service.ChatService;
import com.hwj.service.FollowService;
import com.hwj.service.UserInfoService;
import com.hwj.utils.JsonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@CrossOrigin
@RestController
@RequestMapping("/chat")
@Slf4j
public class ChatController {
    @Autowired
    UserInfoService userInfoService;

    @Autowired
    FollowService followService;

    @Autowired
    ChatService chatService;

    /**
     * 返回好友列表
     * @param request
     * @return
     */
    @GetMapping("/getFriends")
    public JsonResponse getFriends(HttpServletRequest request){
        JWT jwt = JWTUtil.parseToken(request.getHeader("token"));
        Object userId = jwt.getPayload("userId");
        return JsonResponse.successResponse(0,"返回好友列表成功",followService.getFriends(Long.parseLong(userId+"")));
    }

    /**
     * 返回好友帖子列表
     * @param friendId
     * @param request
     * @return
     */
    @GetMapping("/listFriendsPosts")
    public JsonResponse listFriendsPosts(Long friendId,HttpServletRequest request){
        JWT jwt = JWTUtil.parseToken(request.getHeader("token"));
        Object userId = jwt.getPayload("userId");
        return JsonResponse.successResponse(0,"返回好友帖子列表成功",followService.listFriendsPosts(Long.parseLong(userId+""),friendId));
    }

    /**
     * 返回指定好友的聊天记录
     * @param userId
     * @param request
     * @return
     */
    @GetMapping("listChat")
    public JsonResponse listChat(Long userId,HttpServletRequest request){
        JWT jwt = JWTUtil.parseToken(request.getHeader("token"));
        Object loginId = jwt.getPayload("userId");
        return JsonResponse.successResponse(0,"返回好友帖子列表成功",chatService.listChat(Long.parseLong(loginId+""),userId));
    }

    /**
     * 聊天列表
     * @param chat
     * @param request
     * @return
     */
    @PostMapping("")
    public JsonResponse listChat(@RequestBody Chat chat,HttpServletRequest request){
        if(ObjectUtil.isEmpty(chat.getReceiverId())||ObjectUtil.isEmpty(chat.getMessage())){
            return JsonResponse.failResponse(-2,"发送消息失败",null);
        }
        JWT jwt = JWTUtil.parseToken(request.getHeader("token"));
        Object loginId = jwt.getPayload("userId");
        chat.setSenderId(Long.parseLong(loginId+""));
        chatService.insertSelective(chat);
        return JsonResponse.successResponse(0,"发送消息成功",null);
    }


}
